package com.damai.job;

import org.citywithincity.jobqueue.JobException;

import com.damai.lifecycle.JobIoException;
import com.damai.lifecycle.JobNotFoundException;

/**
 * 同步提交任务
 * @author renxueliang
 *
 * @param <T>
 * @param <R>
 */
public abstract class SyncSubmitJob<T,R> {

	/**
	 * 
	 * @param data
	 * @throws JobException 
	 * @throws PosSignError		表示签到错误
	 * @throws PosError			表示交易发生错误
	 * @throws PosIOError		表示3次冲正都没有收到，记录一下io异常
	 */
	public R submit(T data) throws JobIoException, JobException{
		
		for(int i=0; i < 3; ++i){
			try{
				return doSubmit(data);
			}catch(JobIoException e){
				//确认
				try {
					return confirm(data);
				} catch (JobNotFoundException e1) {
					//没有确认成功，需要重新来过
					continue;
				}
				
			}
		}
		//这里可以确认没有创建成功
		throw new JobException();
	}
	
	private R confirm( T data) throws JobIoException, JobNotFoundException {
		JobIoException error = null;
		for(int i=0; i < 3; ++i){
			try {
				return doConfirm( data);
			} catch (JobIoException e) {
				error = e;
				continue;
			}
		}
		//这里表示没有办法确认，这笔只能之后做可疑账分析,或者以后再次确认
		throw error;
	}


	/**
	 * 确认
	 * @param status
	 * @param data
	 * @throws PosError
	 * @throws PosIOError
	 */
	protected abstract R doConfirm(T data) throws JobIoException,JobNotFoundException;
	
	/**
	 * 提交任务
	 * @param data
	 * @return
	 * @throws JobIoException
	 * @throws JobIoException
	 */
	protected abstract R doSubmit(T data) throws JobIoException,JobIoException;
}
